window.download = (url, onsuccess, onerror) => {
	let downloadUrl = url, path = '', name = url;
	if (url.indexOf('/') != -1) {
		path = url.slice(0, url.lastIndexOf('/'));
		name = url.slice(url.lastIndexOf('/') + 1);
	}

	lib.config.brokenFile.add(url);

	if (url.indexOf('http') != 0) {
		url = lib.updateURL + '/master/' + url;
	}

	function success() {
		lib.config.brokenFile.remove(downloadUrl);
		game.saveConfigValue('brokenFile');
		if (typeof onsuccess == 'function') {
			onsuccess();
		}
	}

	function error(e, statusText) {
		if (typeof onerror == 'function') {
			onerror(e, statusText);
		} else console.error(e);
	}

	fetch(url)
		.then(response => {
			const ok = response.ok,
				status = response.status,
				statusText = response.statusText;
			//const { ok, status, statusText } = response;
			if (!ok) {
				return error(status, statusText);
			} else {
				return response.arrayBuffer();
			}
		})
		.then(arrayBuffer => {
			// 写入文件
			if (!arrayBuffer) return;
			game.ensureDirectory(path, () => {
				if (lib.node && lib.node.fs) {
					lib.node.fs.writeFile(__dirname + '/' + path + '/' + name, Buffer.from(arrayBuffer), null, e => {
						if (e) {
							error(e, 'writeFile');
						} else {
							success();
						}
					});
				} 
				else if (typeof window.resolveLocalFileSystemURL == 'function') {
					window.resolveLocalFileSystemURL(lib.assetURL + path, entry => {
						entry.getFile(name, { create: true }, fileEntry => {
							fileEntry.createWriter(fileWriter => {
								fileWriter.onwriteend = () => {
									success();
								};
								fileWriter.write(arrayBuffer);
							}, e => {
								error(e, 'writeFile');
							});
						});
					});
				}
			});

		})
		.catch(error);
};

window.downloadFile = (current, onsuccess, onerror) => {
	// 重新下载
	let reload = (err, statusText) => {
		onerror(current, statusText);
		setTimeout(() => {
			window.downloadFile(current, onsuccess, onerror);
		}, 500);
	};
	// 通过url下载文件
	window.download(current, function success() {
		onsuccess(current);
	}, function error(e, statusText) {
		if (typeof e == 'number') {
			//状态码
			switch (e) {
				case 404:
					console.log({ current, e, statusText: "文件不存在，不需要重新下载" });
					return onsuccess(current, true);
				case 429:
					onerror(current, e, "请求太多，请稍后重新下载");
					break;
				default:
					onerror(current, e, statusText);
			}
		} else if (statusText === 'writeFile') {
			onerror(current, e, '写入文件失败');
		} else {
			onerror(current, e, statusText);
		}
		reload(e, statusText);
	});
};
window.multiDownload = (list, onsuccess, onerror, onfinish) => {
	list = list.slice(0);
	let download = () => {
		if (list.length) {
			let current = list.shift();

			window.downloadFile(current, (current, bool) => {
				onsuccess(current, bool);
				//自调用
				download();
			}, (e, statusText) => {
				onerror(current, e, statusText);
			});

		} else {
			onfinish();
		}
	};
	download();
};
window.auto_update = function () {
	fetch(`${updateURL}versionlist.js`)
		.then(response => {
			if (response.ok) return response.text();
		})
		.then(text => {
			try {
				eval(text);
			} catch (e) {
				return alert('更新内容获取失败，请重试');
			}
			let updatelist = window.updatelist;
			delete window.updatelist;
			let version = window.new_version.version;
			do {
				if (!updatelist[version]) {
					return;
				}
				fetch(`${updateURL}/${updatelist[version]}/game/update.js`)
					.then(response => {
						if (response.ok) return response.text();
					})
					.then(text => {
						try {
							eval(text);
						} catch (e) {
							return alert('更新内容获取失败，请重试');
						}
						let files = window.update.files;
						delete window.update;
						for (let i = 0; i < files.length; i++) {
							if (files[i].indexOf('node_modules/') == 0 /*&& !update.node*/) {
								//只有电脑端用，没有nodejs环境跳过
								if (!lib.node || !lib.node.fs) {
									files.splice(i--, 1);
									continue;
								};
								let entry = files[i];
								lib.node.fs.access(__dirname + '/' + entry, function (err) {
									if (!err) {
										const size = lib.node.fs.statSync(__dirname + '/' + entry).size;
										size == 0 && (err = true);
									}
									!err && files.splice(i--, 1);
								});
							}
						}
						window.multiDownload(updates, (current, bool) => {
							if (bool) {
								console.error(`${current.slice(current.lastIndexOf('/') + 1)}不存在，不需要下载`);
							} else {
								console.log(`${current.slice(current.lastIndexOf('/') + 1)}下载成功`);
							}
							n1++;
							span.innerHTML = `正在下载文件（${n1}/${n2}）`;
						}, (current, e, statusText) => {
							console.error(`${current}下载失败`, { e, statusText });
						}, () => {
						});
					}
					)
					.catch(err => {
						response_catch(err);
						reduction();
					});
			} while (true);

			/*else {
				let num1 = lib.config.version.split('.').map(item => Number(item) || 0).entries();
				let num2 = update.version.split('.').map(item => Number(item) || 0).entries();

				do {
					let next1 = num1.next();
					let next2 = num2.next();

					// 当前游戏版本
					let version1 = next1.value ? next1.value[1] : 0;
					// 要更新的版本，如果当前游戏版本大于这个版本，则提示用户
					let version2 = next2.value ? next2.value[1] : 0;

					if (version1 > version2) {
						if (!confirm('游戏版本比服务器提供的版本还要高，是否覆盖更新？')) {
							game.Updating = false;
							button.innerHTML = '检查游戏更新';
							button.disabled = false;
							return;
						} else {
							break;
						}
					} else if (next1.done && next2.done || version1 < version2) {
						break;
					}
				} while (true);
			}*/
		})
		.catch(err => {
			response_catch(err);
			reduction();
		});
};